package com.yudean.esb.security.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yudean.esb.domain.sys.AppUser;
import com.yudean.esb.mapper.sys.AppUserMapper;
import com.yudean.esb.security.AppUserService;
import com.yudean.esb.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {

    @Resource
    private AppUserMapper appUserMapper;

    /**
     * 分页查询
     * @param currentPage
     * @param pageSize
     * @param appUser
     * @return
     */
    @Override
    public IPage<AppUser> getPage(Integer currentPage, Integer pageSize, AppUser appUser) {
        IPage<AppUser> page = new Page<>(currentPage,pageSize);
        LambdaQueryWrapper<AppUser> lqw = new LambdaQueryWrapper<>();
        lqw.like(Strings.isNotEmpty(appUser.getLoginCode()), AppUser::getLoginCode,appUser.getLoginCode());
        lqw.like(Strings.isNotEmpty(appUser.getLoginName()), AppUser::getLoginName,appUser.getLoginName());
        lqw.like(Strings.isNotEmpty(appUser.getEmail()), AppUser::getEmail,appUser.getEmail());
        lqw.like(Strings.isNotEmpty(appUser.getCompCode()), AppUser::getCompCode,appUser.getCompCode());
        return appUserMapper.selectPage(page,lqw);
    }

    /**
     * 修改用户
     * @param user
     * @return
     */
    @Override
    public int updateSysAppUser(AppUser user) {
        log.info("updateSysAppUser()-request:{loginId:{},loginCode:{},loginName:{},email:{},tel:{},address:{},state:{},compCode:{}}",
                user.getLoginId(),user.getLoginCode(),user.getLoginName(),user.getEmail(),user.getTel(),user.getAddress(),user.getState(),user.getCompCode());

        String password = user.getPassword();
        if(!StringUtil.isEmpty(password)){
            user.setPassword(StringUtil.encodePassword(password, "SHA"));
        }
        //修改对应的公司权限COMP_CODE (table:sys_appuser_org)
        if(!StringUtil.isEmpty(user.getCompCode())) {
            int count = appUserMapper.updateCompCode(user.getLoginId(), user.getCompCode());
        }
        //修改其他用户信息
        return appUserMapper.updateUser(user);
    }

    /**
     * 查询最大id值
     * @return
     */
    @Override
    public int selectMaxId() {
        return appUserMapper.selectMaxId();
    }

    /**
     * 创建用户
     * @param appUser
     * @return
     */
    @Override
    public int createUser(AppUser appUser) {
        int userResult = appUserMapper.createUser(appUser);
        int compCodeResult = appUserMapper.insertCompCode(appUser);
        return userResult+compCodeResult;
    }
}
